package com.sinodata.bsm.cicp.collector.common;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.sinodata.bsm.cicp.collector.Collector;
import com.sinodata.bsm.cicp.exception.CollectorException;
import com.sinodata.bsm.cicp.util.CommandReader;
import com.sinodata.bsm.common.vo.ResPropertyValue;

/**
 * 
 * 此采集器直接将shell的输出返回，其中的regex参数没有用到，后续可能会用上，暂时保留
 * 
 * @author wangpeng
 *
 */

public class ShellCollector extends Collector {

    private static final Logger logger = Logger.getLogger(ShellCollector.class);

    @Override
    public String[] getPropMeta() {
        return new String[] { "result" };
    }

    @Override
    public String[] getParamMeta() {
        return new String[] { "shell", "regex" };
    }

    @Override
    public List<ResPropertyValue> collect(String ip) throws CollectorException {
        String shell = this.paramMap.get("shell");
        String regex = this.paramMap.get("regex");
        String[] props = this.getPropMeta();
        List<ResPropertyValue> values = new ArrayList<ResPropertyValue>();
        BufferedReader reader = null;
        try {
            reader = CommandReader.getReader(ip, shell, (int) this.interval, 0);
            String strLine = null;
            StringBuilder sb = new StringBuilder();
            while ((strLine = reader.readLine()) != null) {
                sb.append(strLine).append("\t");
            }
            ResPropertyValue propertyValueX = new ResPropertyValue();
            ResPropertyValue.PropValue[] propValues = new ResPropertyValue.PropValue[props.length];
            propValues[0] = ResPropertyValue.createPropValue(sb.toString(), props[0]);
            propertyValueX.setValues(propValues);
            values.add(propertyValueX);
            return values;
        } catch (IOException e) {
            logger.error("failed to execite " + shell, e);
            return null;
        }
    }
}
